package novel.front.novellist.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import novel.common.constant.IConstInfo;
import novel.common.utils.weixin.message.HttpUtil;
import novel.common.utils.weixin.wxFxConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import static novel.common.utils.weixin.wxAuth.getWxUserInfo;

/**
 * Created by sutong on 2017/11/26.
 */
@Controller
@RequestMapping("xfx")
public class XfxController {
    public static final String appId = "wx80a6a2244fbb2de9";
    public static final String secret = "d30c23656e12eb812d0ba0b9039357a3";
    @RequestMapping(value = "getWxUser")
    public void getWxUser() throws UnsupportedEncodingException {
        String reUrl="www.kukuwu.com/xfx/getUserInfo";
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx80a6a2244fbb2de9&redirect_uri=" + URLEncoder.encode(reUrl, "UTF-8") + "&response_type=code&scope=snsapi_userinfo#wechat_redirect";
        HttpUtil.sendGet(url, "utf-8", 1000);
    }

    @RequestMapping(value = "getUserInfo")
    public String getUserInfo(String code) {
        String userInfo = getWxUserInfo(code, appId, secret);
//        return userInfo;
        String wxLoginUrl="http://www.kukuwu.com/static/dist/index.html#/index/zh?userInfo="+userInfo;
        return "redirect:"+wxLoginUrl;
    }

    @RequestMapping(value = "test")
    public String test(String code,ModelMap modelMap) {
        String userInfo = getWxUserInfo(code, appId, secret);
        modelMap.addAttribute("userInfo",userInfo);
        return "wx/test";
    }

    @RequestMapping(value = "getWxFxConfig")
    @ResponseBody
    public void getWxFxConfig(HttpServletRequest request,HttpServletResponse response){
        wxFxConfig.signTest();
        String requestUrl = request.getRequestURL().toString();
        Map<String,Object> map= wxFxConfig.getWxConfig(requestUrl, appId, secret);
//        return map;
        PrintWriter out =null;
        try
        {
            out = response.getWriter();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        out.print(JSON.toJSONString(map));
        out.flush();
        out.close();
    }

}
